package com.thingsgrid.appmanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thingsgrid.appmanager.entity.ApplicationBindDevice;
import com.thingsgrid.appmanager.entity.ApplicationInfo;
import com.thingsgrid.appmanager.entity.ApplicationTimes;
import com.thingsgrid.appmanager.entity.FeignVo;
import com.thingsgrid.appmanager.service.IApplicationTimesService;
import com.thingsgrid.appmanager.service.IApplicationsService;
import com.thingsgrid.appmanager.service.IDeviceBindAppService;
import com.thingsgrid.appmanager.util.GetID;
import com.thingsgrid.common.cache.CacheNames;
import com.thingsgrid.device.entity.Device;
import com.thingsgrid.device.feign.TopmFeign;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDateTime;
import java.util.*;

@ApiIgnore
@RestController
@RequestMapping("/AppOperation")
@AllArgsConstructor
public class AppOperationsController extends BladeController implements CacheNames {
	private IApplicationsService service;

	private IDeviceBindAppService disservices;

	private IApplicationTimesService timesService;

	/**
	 * 调用设备模块
	 */
	private TopmFeign topmfeign;

	/**
	 * 查询所有app
	 *
	 * @return
	 */
	@GetMapping("/app")
	@ApiOperation(value = "查询所有app", notes = "查询所有app", position = 1)
	public R<List> showApp() {
		List<ApplicationInfo> list = new ArrayList<>();
		list = service.showApp();
		return R.data(list);
	}

	/**
	 * 分页+条件 查询
	 */
/*	@GetMapping("/pageApp")
	@ApiOperation(value = "分页分条件查询所有app", notes = "分页分条件查询所有app", position = 2)
	public R<List> page(@ApiIgnore String app_name, Float version, @RequestParam String device_id) {
		List<ApplicationInfo> list = service.getApp(app_name, version,device_id);
		return R.data(list);
	}*/
	@GetMapping("/pageApp")
	public R<Page<ApplicationInfo>> pageApp(Page<ApplicationInfo> page, String app_name, Float version, @RequestParam String device_id) {
		Page<ApplicationInfo> ipage = service.getApppage(page, app_name, version, device_id);
		return R.data(ipage);
	}

	/**
	 * 获得设备列表
	 *
	 * @return
	 */
	@PostMapping("/get_device_app")
	@ApiOperation(value = "查询设备以及设备的app", notes = "查询设备以及设备的app", position = 3)
	public R<Map<String, Object>> showDevice(Page page, String deviceName, Integer app_num) {

		ObjectMapper objectMapper = new ObjectMapper();
		List<Device> device_list = new LinkedList<>();
		FeignVo feignVo = new FeignVo();
		feignVo.setCurrent((int) page.getCurrent());
		feignVo.setSize((int) page.getSize());
		feignVo.setDeviceName(deviceName);

		Object obj_total = null;
		Object obj_dev = null;
		int total = -1;
		List<String> devStr = new LinkedList<>();
		if (app_num != null) {

			List<ApplicationTimes> devicelist = timesService.getDeviceByAppnum();
			for (ApplicationTimes app : devicelist) {
				if (app_num.equals(app.getTimes())) {
					devStr.add(app.getDeviceId());
				}
			}
			feignVo.setDeviceIds(devStr);
			if (app_num == 0) {
				feignVo.setFlag(0);
				obj_total = topmfeign.GetSomeDeviceInfo(feignVo).getData().get("total");
				obj_dev = topmfeign.GetSomeDeviceInfo(feignVo).getData().get("device");
				total = objectMapper.convertValue(obj_total, Integer.class);
				device_list = objectMapper.convertValue(obj_dev, new TypeReference<List<Device>>() {
				});
			} else {
				feignVo.setFlag(1);
				obj_total = topmfeign.GetSomeDeviceInfo(feignVo).getData().get("total");
				obj_dev = topmfeign.GetSomeDeviceInfo(feignVo).getData().get("device");
				total = objectMapper.convertValue(obj_total, Integer.class);
				device_list = objectMapper.convertValue(obj_dev, new TypeReference<List<Device>>() {
				});
			}
			List<Map<String, Object>> list = new ArrayList<>();
			for (Device device : device_list) {
				Map<String, Object> map = new HashMap<>();
				map.put("device", device);
				map.put("count", app_num);
				list.add(map);
			}
			Map<String, Object> returnmap = new HashMap<>();
			returnmap.put("total", total);
			returnmap.put("dev", list);
			return R.data(returnmap);
		} else {
			feignVo.setDeviceIds(null);
			feignVo.setFlag(-1);
			System.out.println(feignVo);
			obj_total = topmfeign.GetSomeDeviceInfo(feignVo).getData().get("total");
			obj_dev = topmfeign.GetSomeDeviceInfo(feignVo).getData().get("device");
			total = objectMapper.convertValue(obj_total, Integer.class);
			device_list = objectMapper.convertValue(obj_dev, new TypeReference<List<Device>>() {
			});

			List<Map<String, Object>> list = new ArrayList<>();
			for (Device device : device_list) {
				Map<String, Object> map = new HashMap<>();
				List<ApplicationInfo> returnlist = service.getApplications(device);
				if (returnlist.size() > 0) {
					map.put("device", device);
					map.put("count", returnlist.size());
					list.add(map);
				} else {
					map.put("device", device);
					map.put("count", 0);
					list.add(map);
				}
			}
			Map<String, Object> returnmap = new HashMap<>();
			returnmap.put("total", total);
			returnmap.put("dev", list);
			return R.data(returnmap);
		}
	}

	/**
	 * 保存applist
	 */
	@PostMapping("/saveApp")
	@ApiOperation(value = "保存设备绑定的app", notes = "保存设备绑定的app", position = 4)
	public R saveApp(@ApiParam("app列表") @RequestParam String applist, @RequestParam String device_id) {
		List<ApplicationBindDevice> list = new ArrayList<>();
		List<String> result = Arrays.asList(applist.split(","));
		GetID getID;
		for (int i = 0; i < result.size(); i++) {
			ApplicationBindDevice appBindDevice = new ApplicationBindDevice();
			getID = new GetID();
			appBindDevice.setId(getID.getTemp());
			appBindDevice.setApplicationId(result.get(i));
			appBindDevice.setAppState(0);
			appBindDevice.setDeviceId(device_id);
			appBindDevice.setUpgradeType(0);
			appBindDevice.setDeviceId(device_id);
			appBindDevice.setCreateTime(LocalDateTime.now());
			appBindDevice.setUpgradeTime(LocalDateTime.now());
			appBindDevice.setCreateUser("zhangsan");
			list.add(appBindDevice);

		}
		return R.status(disservices.saveBatch(list));
	}

	/**
	 * 删除指定的app
	 *
	 * @param app_id
	 * @param device_id
	 * @return
	 */
	@PostMapping("/deleteApp")
	@ApiOperation(value = "删除指定app", notes = "删除指定app", position = 5)
	public R deleteApp(@ApiParam("删除的appid") @RequestParam String app_id, @RequestParam String device_id) {
		UpdateWrapper<ApplicationBindDevice> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("device_id", device_id);
		updateWrapper.eq("application_id", app_id);
		updateWrapper.set("app_state", 2);
		return R.status(disservices.update(updateWrapper));
	}

	/**
	 * 批量删除app列表
	 *
	 * @param ids
	 * @param device_id
	 * @return
	 */
	@PostMapping("/deleteApps")
	@ApiOperation(value = "删除指定app列表", notes = "删除指定app列表", position = 6)
	public R deleteApps(@RequestParam String ids, @RequestParam String device_id) {
		UpdateWrapper<ApplicationBindDevice> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("device_id", device_id);
		updateWrapper.inSql("application_id", ids);
		updateWrapper.set("app_state", 2);
		return R.status(disservices.update(updateWrapper));
	}

	/**
	 * 启用设备中停用的的APP
	 *
	 * @param app_id
	 * @param device_id
	 * @return
	 */
	@PostMapping("/startuse")
	@ApiOperation(value = "启用设备中的某个app", notes = "启用设备中的某个app", position = 7)
	public R startUse(@RequestParam String app_id, @RequestParam String device_id) {
		UpdateWrapper<ApplicationBindDevice> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("device_id", device_id);
		updateWrapper.eq("application_id", app_id);
		updateWrapper.set("app_state", 0);
		return R.status(disservices.update(updateWrapper));
	}

	/**
	 * 停用当前设备中的某个app
	 *
	 * @param app_id
	 * @param device_id
	 * @return
	 */
	@PostMapping("/stopuse")
	@ApiOperation(value = "停用设备中的某个app", notes = "停用设备中的某个app", position = 8)
	public R stopUse(@RequestParam String app_id, @RequestParam String device_id) {
		UpdateWrapper<ApplicationBindDevice> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("device_id", device_id);
		updateWrapper.eq("application_id", app_id);
		updateWrapper.set("app_state", 1);
		return R.status(disservices.update(updateWrapper));
	}

	/**
	 * 获得当前设备的app
	 * 参数1：current：当前页，size：每页大小
	 * 参数2：device_id: 设备id
	 */
	@PostMapping("/searchAppByDevice")
	@ApiOperation(value = "根据设备标识获取app", notes = "根据设备标识获取app", position = 9)
	public R<Map<String, Object>> searchAppByDevice(@RequestParam String device_id, Page<ApplicationInfo> p, Float version, String app_name) {
		List<Map> list = new LinkedList<>();
		Page<ApplicationInfo> page = service.selectAppPage(p, device_id, version, app_name);
		Long total = page.getTotal();
		for (ApplicationInfo applicationInfo : page.getRecords()) {
			Map<String, Object> map = new HashMap<>();
			Float v = service.getNewVersion(applicationInfo.getId());
			String app_id = applicationInfo.getId();
			QueryWrapper<ApplicationBindDevice> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("application_id", app_id);
			queryWrapper.eq("device_id", device_id);
			int status = disservices.getOne(queryWrapper).getAppState();
			map.put("app", applicationInfo);
			map.put("state", status);
			map.put("newVersion", v);
			list.add(map);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("applist", list);
		map.put("total", total);
		return R.data(map);
	}


}
